'use strict';

const Controller = require('egg').Controller;

class AgentController extends Controller {
    //代理 列表
    async list() {
        const { ctx, app } = this;
        const uid = ctx.wxUser.id
        let list = await ctx.page(app.model.CouponsAgent, { wx_user_id: uid }, {
            include: [{
                model: app.model.Coupons,
                attributes: ['id', 'shop_id', 'title', 'pay_price', 'market_price', 'end_time'],
                include: [
                    {
                        model: app.model.Shop,
                        attributes: ['id', 'title', 'logo', 'banner']
                    }
                ]
            }]
        })
        let newtime = new Date().getTime(), state
        list.rows = list.rows.map(item => {
            if (item.coupon.end_time < newtime) {
                state = '已过期'
            } else {
                if (item.share_num == item.agent_num) {
                    state = "已推广完"
                } else {
                    state = "推广"
                }
            }
            return {
                id: item.id,
                wx_user_id: item.wx_user_id,
                coupons_id: item.coupons_id,
                agent_num: item.agent_num,
                share_num: item.share_num,
                shop_id: item.coupon.shop_id,
                coupon_title: item.coupon.title,
                pay_price: item.coupon.pay_price,
                market_price: item.coupon.market_price,
                end_time: item.coupon.end_time,
                shop_title: item.coupon.shop.title,
                shop_logo: item.coupon.shop.logo,
                shop_image: item.coupon.shop.banner ? item.coupon.shop.banner.split(',')[0] : '',
                state
            }
        })
        ctx.apiSuccess(list)
    }
    //代理 券详情
    async listone() {
        const { ctx, app } = this;
        ctx.validate({
            coupons_id: {
                type: 'int',
                required: true,
                desc: '券id'
            }
        })
        const { coupons_id } = ctx.query
        let list = await app.model.Coupons.findOne({
            where: {
                id: coupons_id
            },
            attributes: ['id', 'detail', 'use_otice', 'goods_detaill', 'coupon_limit', 'agent_otice']
        })
        ctx.apiSuccess(list)
    }
    //推广 二维码
    async qrcode() {
        const { ctx, app } = this
        const uid = ctx.wxUser.id
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: '代理券id'
            }
        })
        const { id } = ctx.query
        let list = await app.model.CouponsAgent.findOne({
            where: {
                id,
                wx_user_id: uid
            }
        })
        if (!list) {
            ctx.throw(400, '代理券不存在')
        }
        let alist = {
            id,
            type: 'agent'
        }
        ctx.qrcode(alist)
    }
    
   

    //收益 列表
    async profitlist() {
        const { ctx, app } = this
        const { year, month } = ctx.query
        const uid = ctx.wxUser.id
        ctx.validate({
            year: {
                type: 'int',
                required: true,
                range: {
                    min: 2020,
                    max: 2099
                },
                desc: '查询年'
            },
            month: {
                type: 'int',
                required: true,
                range: {
                    min: 1,
                    max: 12
                },
                desc: '查询月'
            }
        })
        let aa = this.getMonthDateRange(year, month)
        let list, Op = app.Sequelize.Op;
        list = await ctx.page(app.model.Profit, {
            created_at: {
                [Op.between]: [aa.start, aa.end]
            },
            type: 'wxuser',
            type_id: uid
        })
        let total_revenue = 0
        list.rows.forEach(item => {
            // console.log(item.price)
            if (item.price.indexOf('+') > -1) {
                total_revenue = total_revenue + parseFloat(item.price.slice(1))
            } else {
                total_revenue = total_revenue - parseFloat(item.price.slice(1))
            }
        });
        this.ctx.apiSuccess({ list, total_revenue })
    }
    //提现记录
    async cashoutlist() {
        const { ctx, app } = this
        const uid = ctx.wxUser.id
        let list = await ctx.page(app.model.Cashout, {
            type: 'wxuser',
            type_id: uid
        })
        ctx.apiSuccess(list)
    }
    //申请提现
    async cashoutadd() {
        const { ctx, app } = this
        const { id, nickname } = ctx.wxUser
        const { price, bank_id } = ctx.request.body;
        ctx.validate({
            price: {
                type: 'int',
                required: true,
                desc: '提现金额'
            },
            bank_id: {
                type: 'int',
                required: true,
                desc: '银行卡id'
            }
        })
        let bankone = await app.model.Bank.findOne({
            where: {
                id: bank_id,
                type: 'wxuser',
                type_id: id
            },
            attributes: ['name', 'code', 'bank_branch'],
            include: [
                {
                    model: app.model.BankConfig,
                    as:'bankconfig',
                    attributes: ['title']
                }
            ]
        })
        let user = await app.model.WxUser.findOne({
            where: {
                id
            },
            attributes: ['id', 'withdrawal_price', 'status']
        })
        if (user.withdrawal_price < price) {
            ctx.throw(400, '提现金额不足')
        }
        let content = `${nickname}提现${price}到-${bankone.bankconfig.title}-${bankone.code}-${bankone.name}-${bankone.bank_branch}-账户`
        let transaction
        try {
            // 开启 事务
            transaction = await app.model.transaction();
            // 我的信息表 操作
            await user.update({
                withdrawal_price: user.withdrawal_price - price
            }, { transaction })
            // 提现表 操作
            await app.model.Cashout.create({
                type: 'wxuser',
                type_id: id,
                content,
                price,
            }, { transaction })
            // 提交事务
            await transaction.commit();
            return ctx.apiSuccess('操作成功');
        } catch (e) {
            // 事务回滚
            await transaction.rollback();
            return ctx.apiFail('操作失败');
        }
        // ctx.apiSuccess({bankone,content})
    }
    //计算一个月开始 结束时间
    getMonthDateRange(year, month) {
        var moment = require('moment');
        var startDate = moment([year, month - 1]);
        var endDate = moment(startDate).endOf('month');
        return { start: startDate, end: endDate };
    }
}

module.exports = AgentController;
